//
//  XGL_PersonalVideoSegmentView.swift
//  XGamesLive
//
//  Created by ios on 2024/5/17.
//

import UIKit
import MJRefresh

class XGL_PersonalVideoSegmentView: PanSegmentView {
    
    var collectionView: UICollectionView!
    var videosData: [PublishData] = []
    var pageIndex: NSInteger = 1

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        let waterfallLayout = WaterfallLayout()
        waterfallLayout.delegate = self
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: waterfallLayout)
        collectionView.register(XGL_VideoItemCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        self.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        header.setTitle("Pull down refresh", for: .idle)
        header.setTitle("Release update", for: .pulling)
        header.setTitle("Refresh...", for: .refreshing)
        header.setRefreshingTarget(self, refreshingAction: #selector(self.refresh))
        collectionView.mj_header = header
        footer.setTitle("No more data", for: .noMoreData)
        footer.setRefreshingTarget(self, refreshingAction: #selector(self.getMore))
        collectionView.mj_footer = footer
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension XGL_PersonalVideoSegmentView{
    @objc private func refresh(){
        self.delegate?.refresh(view: self)
    }
    @objc private func getMore(){
        self.delegate?.getMore(view: self)
    }
    
    @objc private func thumbItemAction(sender: UIButton){
        sender.isSelected = !sender.isSelected
        let index = sender.tag - 2300
        self.thumbRequest(id: self.videosData[index].id, isThumb: sender.isSelected, index: index)
    }
}

extension XGL_PersonalVideoSegmentView{
    func thumbRequest(id: String,isThumb: Bool,index: NSInteger){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .Handler(auditTreeDataId: id, type: 2, actionResult: isThumb))) { result in
            switch result{
            case .success(let response):
                if self.segmentType == 2{
                    self.videosData.remove(at: index)
                    self.collectionView.reloadData()
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_PersonalVideoSegmentView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.videosData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! XGL_VideoItemCollectionViewCell
        cell.itemData = videosData[indexPath.item]
        cell.complete = { image in
            self.collectionView.reloadItems(at: [indexPath])
        }
        cell.thumbItem.tag = indexPath.row + 2300
        cell.thumbItem.addTarget(self, action: #selector(self.thumbItemAction(sender:)), for: .touchUpInside)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.delegate?.didSelectRow(view: self, section: indexPath.section, index: indexPath.row)
    }
}

extension XGL_PersonalVideoSegmentView: WaterfallLayoutDelegate {
    func waterfallLayout(_ waterfallLayout: WaterfallLayout, heightForItemAtIndex index: Int, itemWidth: CGFloat) -> CGFloat {
        let model = videosData[index]
        var imageUrl = ""
        if model.data4 == "2"{
            if let url = model.data7 {
                imageUrl = url
            }
        }else{
            if let url = model.data3?.components(separatedBy: ",").first{
                imageUrl = url
            }
        }
        var scale = 150.0 / 234.0
        let cache = XGL_WaterfallImageCacheManager.shared.infor
        if let imageData = cache.imageDic[imageUrl],let image = UIImage(data: imageData) {
            scale = image.size.width / image.size.height
        }
        return conversionWithScrennWidth(value: itemWidth / scale)
    }
    
    func colCountInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> Int { 2 }
    
    func colMarginInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> CGFloat { 8 }
    
    func rowMarginInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> CGFloat { 16 }
    
//    func edgeInsetsInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> UIEdgeInsets {
//        var safeAreaInsets: UIEdgeInsets = UIApplication.shared.keyWindow?.safeAreaInsets ?? .zero
//        safeAreaInsets.top += 44 + 5
//        safeAreaInsets.left += 5
//        safeAreaInsets.bottom += 49 + 5
//        safeAreaInsets.right += 5
//        return safeAreaInsets
//    }
}
